package com.atguigu.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.commonutils.R;
import com.atguigu.servicebase.exceptionhandler.SelfExceptionHandler;
import com.atguigu.vod.service.VodService;
import com.atguigu.vod.utils.ConstantVodUtils;
import com.atguigu.vod.utils.InitVodClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class VodController {

    @Autowired
    private VodService vodService;

    /**
     * 上传一个视频
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R uploadVideo(MultipartFile file) {
        //上传视频，返回视频id(唯一）
        String videoId=vodService.uploadVideo(file);
        System.out.println(videoId);
        return R.ok().data("videoId",videoId);
    }

    /**
     * 根据视频id删除视频
     * 在sdk的媒资管理
     * @param videoId
     * @return
     */
    @DeleteMapping("/removeVideo/{videoId}")
    public R removeVideo(@PathVariable String videoId) {
        boolean isDelete=vodService.removeVideo(videoId);
        if (isDelete)
        return R.ok();
        else
        throw  new SelfExceptionHandler("删除单个视频失败",20001);
    }

    /**
     * 删除课程批量删除视频
     * @param list
     * @return
     */
    @DeleteMapping("/removeVideoBatch")
    public R removeVideoBatch(@RequestParam("list") List<String> list) {
        boolean isDelete=vodService.removeVideoBatch(list);
        if (isDelete)
            return R.ok();
        else
            throw  new SelfExceptionHandler("批量删除失败",20001);

    }


    //根据视频id获取视频凭证
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id) {
        try {
            //创建初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建获取凭证request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            //向request设置视频id
            request.setVideoId(id);
            //调用方法得到凭证
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            return R.ok().data("playAuth",playAuth);
        }catch(Exception e) {
            throw new SelfExceptionHandler("获取凭证失败",20001);
        }
    }

}
